<template>
  <tn-navbar 
    :bottom-shadow="false"
    fixed
  >
    <text class="title">领取挪车码</text>
  </tn-navbar>
  <view class="container">
    <view class="form-container">
      <view class="form-item">
        <view class="form-header">
          <text class="form-label">车牌号码</text>
          <view class="new-energy-option">
            <text class="new-energy-text">新能源车牌</text>
            <switch 
              :checked="isNewEnergyVehicle"
              @change="handleNewEnergyChange"
              color="#1aad19"
              style="transform: scale(0.8);"
            />
          </view>
        </view>
        <view class="license-plate-container" @tap="openKeyboard">
          <!-- 车牌号码方格显示 -->
          <view class="plate-grid-container">
            <!-- 省份简称格子 -->
            <view class="plate-grid plate-grid-province" :class="{ 'active': keyboardValue.length === 0 }">
              <text class="plate-text">{{ keyboardValue[0] || '' }}</text>
            </view>
            <!-- 字母和数字格子 - 根据是否新能源显示6个或7个 -->
            <view 
              v-for="(_, index) in (isNewEnergyVehicle ? 7 : 6)" 
              :key="index + 1" 
              class="plate-grid" 
              :class="{ 'active': keyboardValue.length === index + 1 }"
            >
              <text class="plate-text">{{ keyboardValue[index + 1] || '' }}</text>
            </view>
          </view>
        </view>
        <text class="tip-text" v-if="!keyboardValue">点击输入车牌号码，通知时使用</text>
      </view>

      <view class="form-item">
        <text class="form-label">备注</text>
        <textarea
            class="form-textarea"
            placeholder="请输入备注信息（选填）"
            v-model="vehicleForm.remark"
        ></textarea>
      </view>

      <view class="form-item">
        <text class="form-label">默认留言</text>
        <textarea
          class="form-textarea message-textarea"
          placeholder="请输入默认留言，如：如需挪车请联系物业，谢谢配合"
          v-model="vehicleForm.message"
          maxlength="100"
        ></textarea>
        <text class="word-count">{{ vehicleForm.message.length }}/100</text>
        <text class="message-tip">此留言将显示在扫码页面，方便他人了解您的要求</text>
      </view>

      <view class="form-item">
        <view class="notification-header">
          <text class="form-label">自定义通知设置</text>
          <switch 
            :checked="vehicleForm.notification.enabled"
            @change="handleSwitchChange"
            color="#1aad19"
          />
        </view>
        
        <view v-if="vehicleForm.notification.enabled" class="webhook-container">
          <input
            class="webhook-input"
            type="text"
            v-model="vehicleForm.notification.webhookUrl"
            placeholder="请输入Webhook地址"
          />
          <text class="webhook-tip">当有人扫码时，系统会向该地址发送通知而不是全局webhook地址</text>
        </view>
      </view>
    </view>

    <view class="form-actions">
      <button class="submit-btn" @tap="handleSubmit">领 取</button>
    </view>
    
    <view class="info-card">
      <view class="info-icon">
        <text class="iconfont icon-info"></text>
      </view>
      <view class="info-text">
        <text>领取挪车码后，可下载挪车码图片，用于张贴在车辆上</text>
      </view>
    </view>
  </view>

  <!-- 车牌号输入键盘 - 去掉震动效果 -->
  <TnKeyboard
      v-model="keyboardValue"
      v-model:show="showKeyboard"
      mode="car"
      :vibrate="false"
      @confirm="onKeyboardConfirm"
  />
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import TnKeyboard from '@/uni_modules/tuniaoui-vue3/components/keyboard/src/keyboard.vue'

// 车辆表单数据
const vehicleForm = ref({
  licensePlate: '',
  remark: '',
  message: '',
  notification: {
    enabled: false,
    webhookUrl: ''
  }
});

// 键盘相关
const showKeyboard = ref(false);
const keyboardValue = ref('');
// 新能源车牌标志
const isNewEnergyVehicle = ref(false);

// 监听键盘值变化，同步到车牌号，根据是否新能源车牌限制最大长度
watch(keyboardValue, (newValue) => {
  const maxLength = isNewEnergyVehicle.value ? 8 : 7;
  if (newValue.length <= maxLength) {
    vehicleForm.value.licensePlate = newValue;
  } else {
    keyboardValue.value = newValue.slice(0, maxLength);
  }
});

// 处理新能源车牌开关变化
const handleNewEnergyChange = (e: any) => {
  isNewEnergyVehicle.value = e.detail.value;
  // 如果从新能源切换到普通车牌，且当前输入超过7位，则截断
  if (!isNewEnergyVehicle.value && keyboardValue.value.length > 7) {
    keyboardValue.value = keyboardValue.value.slice(0, 7);
    vehicleForm.value.licensePlate = keyboardValue.value;
  }
};

// 打开键盘
const openKeyboard = () => {
  keyboardValue.value = vehicleForm.value.licensePlate;
  showKeyboard.value = true;
};

// 修复 switch 事件处理函数
const handleSwitchChange = (e: any) => {
  vehicleForm.value.notification.enabled = e.detail.value;
};

// 键盘确认 - 修复类型
const onKeyboardConfirm = (value: string) => {
  showKeyboard.value = false;
};

// 导航返回
const navigateBack = () => {
  uni.navigateBack();
};

// 表单提交
const handleSubmit = async() => {
  // 表单验证 - 改用 keyboardValue 来验证
  if (!keyboardValue.value) {
    uni.showToast({
      title: '请输入车牌号码',
      icon: 'none'
    });
    return;
  }

  // 提交前确保车牌号同步
  vehicleForm.value.licensePlate = keyboardValue.value;

  // 如果启用通知但未填写webhook地址
  if (vehicleForm.value.notification.enabled && !vehicleForm.value.notification.webhookUrl) {
    uni.showToast({
      title: '请输入Webhook地址',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 使用模拟数据替代API调用
    const templates = uni.getStorageSync('subMessageTemplateList');
    if(templates){
      // 模拟订阅消息结果
      console.log('模拟订阅消息模板:', templates);
      
      // 模拟成功订阅
      setTimeout(() => {
        uni.showToast({
          title: '订阅成功',
          icon: 'success',
          duration: 1500
        });
      }, 300);
    }
  } catch (error) {
    console.error('订阅消息失败:', error);
  }
  
  // 提交表单
  uni.showLoading({
    title: '保存中...'
  });
  
  // 模拟API调用
  setTimeout(() => {
    // 模拟成功响应
    const mockResponse = {
      code: 200,
      msg: "success",
      data: {
        id: 11,
        license_plate: vehicleForm.value.licensePlate,
        remark: vehicleForm.value.remark,
        message: vehicleForm.value.message,
        code: "mock" + Math.random().toString(36).substring(2, 8),
        qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/mock/qrcode.png",
        move_count: 0,
        notification_enabled: vehicleForm.value.notification.enabled ? 1 : 0,
        webhook_url: vehicleForm.value.notification.webhookUrl,
        status: 1,
        user_id: 12,
        update_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
        instime: Math.floor(Date.now() / 1000),
        itime: new Date().toISOString().replace('T', ' ').substring(0, 19),
        is_del: 0
      }
    };
    
    console.log('模拟添加车辆响应:', mockResponse);
    
    uni.hideLoading();
    uni.showToast({
      title: '领取成功',
      icon: 'success'
    });

    // 返回上一页
    setTimeout(() => {
      navigateBack();
    }, 1500);
  }, 1000);
};
</script>

<style>
.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
.container {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  padding: 40rpx 30rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;
  display: flex;
  flex-direction: column;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

/* 修改表单头部样式，使标题和开关在同一行 */
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.new-energy-option {
  display: flex;
  align-items: center;
}

.new-energy-text {
  font-size: 26rpx;
  color: #666;
  margin-right: 5rpx;
}

/* 车牌输入框样式 */
.license-plate-container {
  position: relative;
  width: 100%;
  height: 110rpx;
  border-radius: 12rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.plate-grid-container {
  display: flex;
  width: 100%;
  height: 90rpx;
  justify-content: center;
}

.plate-grid {
  width: 70rpx; /* 稍微调小一点宽度，以适应8个格子 */
  height: 90rpx;
  border: 1rpx solid #ddd;
  margin: 0 4rpx; /* 减小间距 */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.plate-grid-province {
  background-color: #1aad19;
  color: white;
  border: none;
}

.plate-grid.active {
  border-color: #1aad19;
  border-width: 2rpx;
  transform: scale(1.05);
  box-shadow: 0 4rpx 8rpx rgba(26, 173, 25, 0.2);
}

.plate-text {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.plate-grid-province .plate-text {
  color: white;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  text-align: center;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
}

.submit-btn {
  width: 90%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  border-radius: 45rpx;
  font-size: 32rpx;
  font-weight: bold;
  background-color: #1aad19;
  color: white;
  box-shadow: 0 6rpx 12rpx rgba(26, 173, 25, 0.3);
  letter-spacing: 4rpx;
  transition: all 0.2s ease;
}

.submit-btn:active {
  transform: scale(0.98);
  box-shadow: 0 3rpx 6rpx rgba(26, 173, 25, 0.2);
}

.info-card {
  background-color: #fff8e6;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.info-icon {
  margin-right: 15rpx;
  color: #ff9900;
  font-size: 36rpx;
}

.info-text {
  font-size: 26rpx;
  color: #666;
  flex: 1;
}

/* 假设使用了一个图标字体 */
@font-face {
  font-family: 'iconfont';
  src: url('data:font/woff2;charset=utf-8;base64,...') format('woff2');
}

.iconfont {
  font-family: "iconfont" !important;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-info:before {
  content: "\e6e5"; /* 这里使用的是示例，实际应该使用您项目中的图标编码 */
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.webhook-container {
  margin-top: 20rpx;
}

.webhook-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.webhook-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  display: block;
}

/* 添加留言相关样式 */
.message-textarea {
  width: 100%;
  height: 160rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
  box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 10rpx;
}

.word-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
  display: block;
  margin-bottom: 10rpx;
}

.message-tip {
  font-size: 24rpx;
  color: #999;
  display: block;
}

/* 添加新能源车牌选项样式 */
.plate-options {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10rpx;
}

.new-energy-option {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.new-energy-text {
  font-size: 26rpx;
  color: #666;
  margin-left: 5rpx;
}
</style> 